package com.lpfy.dtxc.playerView;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.lpfy.dtxc.BVImageBean;
import com.tencent.dtxc.R;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: hanGuangHui
 * @data: 2024/2/27
 * @description: 资源播放
 */
public class FilePlayerView2 extends FrameLayout {

    private View mView;

    private int currentPosition = -1;

    private ImageView imageView;
    private VideoView videoView;
    private List<BVImageBean> fileBean;

    private Map<Integer,WebView> webViewList = new HashMap<>();

    private ViewGroup webViewContainer;

    private Handler playerHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (getContext() == null) {
                return;
            }
            if (imageView != null) {
                imageView.setVisibility(View.GONE);
            }
            if (videoView != null) {
                videoView.setVisibility(View.GONE);
            }
            for (int i = 0; i < webViewContainer.getChildCount(); i++) {
                WebView webView = (WebView) webViewContainer.getChildAt(i);
                webView.onPause();
            }
            webViewContainer.setVisibility(View.GONE);
            onPause(videoView);
            String duration = String.valueOf(fileBean.get(currentPosition).getDuration());
            Log.e("-----资源类型" + fileBean.get(currentPosition).getFileType(), duration);
            switch (fileBean.get(currentPosition).getFileType()) {
                case "image":
                    if (imageView != null) {
                        imageView.setVisibility(View.VISIBLE);
                        if (!TextUtils.isEmpty(fileBean.get(currentPosition).getFilePath()) && getContext() != null) {
                            Glide.with(getContext())
                                    .load(fileBean.get(currentPosition).getFilePath())
                                    .into(imageView);
                        }
                    }
                    playerHandler.postDelayed(() -> startPlayer(),
                            fileBean.get(currentPosition).getDuration());
                    break;
                case "video":
                    if (videoView != null) {
                        videoView.setVisibility(View.VISIBLE);
                        start(videoView, fileBean.get(currentPosition).getFilePath());
                    }
                    break;
                case "web":
                    webViewContainer.setVisibility(View.VISIBLE);
                    try {
                        for (int i = 0; i < webViewContainer.getChildCount(); i++) {
                            webViewContainer.getChildAt(i).setVisibility(View.GONE);
                        }
                        int child = webViewContainer.indexOfChild(webViewList.get(currentPosition));
                        WebView webView = (WebView) webViewContainer.getChildAt(child);
                        webView.onResume();
                        webView.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    playerHandler.postDelayed(() -> {
                        startPlayer();
                    }, fileBean.get(currentPosition).getDuration());
                    break;
            }
            if (currentPosition == fileBean.size() - 1) {
                currentPosition = -1;
            }
        }
    };


    private void startPlayer() {
        currentPosition++;
        playerHandler.sendEmptyMessage(0);
    }

    public FilePlayerView2(@NonNull Context context) {
        super(context);
    }

    public FilePlayerView2(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public void initView() {
        mView = LayoutInflater.from(getContext()).inflate(R.layout.view_file_play, this, true);
        imageView = mView.findViewById(R.id.banner_image);
        videoView = mView.findViewById(R.id.banner_video);
        webViewContainer = mView.findViewById(R.id.webViewContainer);
    }

    public void setData(List<BVImageBean> fileBean) {
        if (fileBean == null || fileBean.size() <= 0) {
            return;
        }
        //释放webView
        for (int i = 0; i < webViewContainer.getChildCount(); i++) {
            WebView webView = (WebView) webViewContainer.getChildAt(i);
            webView.destroy();
            webView.removeAllViews();
            webView.reload();
            webView = null;
        }
        webViewContainer.removeAllViews();
        webViewList.clear();
        //循环创建多个webview
        for (int i = 0; i < fileBean.size(); i++) {
            if (fileBean.get(i).getFileType().equals("web")) {
                WebView webView = new WebView(getContext());
                initWebView(webView);
                webView.loadUrl(fileBean.get(i).getFilePath());
                webViewList.put(i,webView);
                webViewContainer.addView(webView);
            }
        }
        currentPosition = -1;
        playerHandler.removeCallbacksAndMessages(null);
        this.fileBean = fileBean;
        startPlayer();
    }


    /**
     * 开始播放
     */
    public void start(VideoView videoView, String url) {
        videoView.setVideoURI(Uri.parse(url));
        MediaController mediaController = new MediaController(getContext());
        videoView.setMediaController(mediaController);
        videoView.setOnCompletionListener(mp -> {
            startPlayer();
        });
        videoView.start(); //开始播放，不调用则不自动播放
    }

    public void onPause(VideoView videoView) {
        if (videoView != null) {
            videoView.pause();
        }
    }

    private void initWebView(WebView mWebView) {
        if (mWebView == null) {
            return;
        }
        WebSettings webSetting = mWebView.getSettings();
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webSetting.setAllowFileAccess(true);
        webSetting.setSupportZoom(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSetting.setAppCacheEnabled(true);
        webSetting.setBlockNetworkImage(false);//解决图片不显示
        webSetting.setJavaScriptEnabled(true);
        webSetting.setMediaPlaybackRequiresUserGesture(false);
        mWebView.setWebViewClient(new WebViewClient() {
            // 解决H5的音视频不能自动播放的问题
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //                String js = "javascript:";
//                js += "var videos = document.getElementsByTagName('video');";
//                js += "var video_last;";
//                js += "var video = videos[videos.length-1];";
//                js += "if (video != undefined && video != video_last) {";
//                {
//                    js += "video_last = video;";
//                    js += "function video_start() {";
//                    {
//                        js += "_VideoEnabledWebView.notifyVideoStart();";
//                    }
//                    js += "}";
//                    js += "video.addEventListener('play', video_start);";
//                }
//                js += "}";
//                view.loadUrl(js);
                mWebView.loadUrl("javascript:(function() { "
                        + "var videos = document.getElementsByTagName('video');"
                        + " for(var i=0;i<videos.length;i++){videos[i].play();}})()");
            }
        });
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.setWebChromeClient(new WebChromeClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0开始，https不能加载http资源，需要添加一下代码
            webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    public void onDestroy() {
        if (videoView != null) {
            videoView.pause();
            videoView = null;
        }
        for (int i = 0; i < webViewContainer.getChildCount(); i++) {
            WebView webView = (WebView) webViewContainer.getChildAt(i);
            webView.destroy();
        }
        playerHandler.removeCallbacksAndMessages(null);
    }
}
